package com.boho.system.service;

/**
 * @File name:  ValidateCodeBusiness.java 
 * @Create on:  2010-05-10
 * @Author   :  陈伟
 *
 * @ChangeList
 * ---------------------------------------------------
 * Date         Editor              ChangeReasons
 *
 **/




import cn.boho.framework.context.ActionContext;
import cn.boho.framework.exception.UserOperationException;
import cn.boho.framework.log.Logger;
import cn.boho.framework.service.MessageService;

import com.boho.common.Constant;

/**
 * 验证码业务类
 * 
 */
public class ValidateCodeService{
	//日志
	private static Logger logger = new Logger(org.apache.log4j.Logger.getLogger(ValidateCodeService.class));
	
	//验证码SESSION默认名称
	private static final String DEFAULT_SESSION_VALIDATE_CODE = "VALIDATE_CODE";
	
	/**
	 * 校验验证码
	 * @param atx
	 * @param validateCode 验证码
	 * @param name 验证码SESSION名称
	 * @param sensitiveCase 是否区分大小写
	 * @throws Exception
	 */
	public static void checkValidateCode(ActionContext atx,String validateCode,String name,boolean sensitiveCase) throws Exception{
		//记录日志
		StringBuffer info=new StringBuffer();
		info.append("\n【验证图片验证码】")
			.append("\nIP："+atx.getRemoteAddr())
			.append("\n操作用户ID："+atx.getStringValue(Constant.SESSION_USER_NO))
			.append("\n验证码："+validateCode)
			.append("\nSESSION名称："+name);
		logger.info(info.toString());
		
		UserOperationException uoe = new UserOperationException();
		//获得验证码
		String sessionName = name==null?DEFAULT_SESSION_VALIDATE_CODE:name;
		String sessionValidateCode = (String)atx.getSessionValue(sessionName);
		//验证码失效
		atx.setSessionValue(sessionName, null);
		//校验验证码
		boolean flag;
		if(sensitiveCase){
			flag=validateCode.equals(sessionValidateCode);
		}else{
			flag=validateCode.equalsIgnoreCase(sessionValidateCode);
		}
		if(!flag){
			atx.setErrorContext("FSTI_SYS_VALID_1001", MessageService.getMessage("FSTI_SYS_VALID_1001"), uoe);
			throw uoe;
		}
	}
	
	/**
	 * 校验验证码，不区分大小写
	 * @param atx
	 * @param validateCode 验证码
	 * @param name 验证码SESSION名称
	 * @throws Exception
	 */
	public static void checkValidateCode(ActionContext atx,String validateCode,String name) throws Exception{
		checkValidateCode(atx,validateCode,name,false);
	}
	
	/**
	 * 校验验证码，不区分大小写
	 * @param atx
	 * @param validateCode 验证码
	 * @throws Exception
	 */
	public static void checkValidateCode(ActionContext atx,String validateCode) throws Exception{
		checkValidateCode(atx,validateCode,null,false);
	}
}
